package com.jpa.security;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;

import com.jpa.dao.PermissionDao;
import com.jpa.dao.RoleDao;
import com.jpa.dao.UserDao;
import com.jpa.pojo.Permission;
import com.jpa.pojo.Role;
import com.jpa.pojo.User;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private final static Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	UserDao usersDao;
	@Autowired
	RoleDao roleDao;
	@Autowired
	PermissionDao permissionDao;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("\n\t loadUserByUsername: ===========>" + username);
		//查找用户
	    User user = usersDao.findByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户名不存在！");
		}
		// 权限
		List<Permission> permissions = permissionDao.findPermissions(user.getUid()); 
		// 角色
		List<Role> roles = roleDao.findRoles(user.getUsername());
		//授权的权限集合
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

		for (Permission p : permissions) { 
			Role role = new Role();
			role.setName(p.getName());
			roles.add(role); 
		}
		logger.info("\n\t Roles ：" + roles);
		for (Role r : roles) { 
			GrantedAuthority g = new SimpleGrantedAuthority(r.getName());
			grantedAuthorities.add(g);
		} 
		logger.info("\n\t 用户名：" + user.getUsername() + "\n\t " + "权限" + grantedAuthorities);
		return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
				grantedAuthorities);
	} 
} 